import { createRouter, createWebHashHistory } from "vue-router";
import Login from "../views/Login";
const Home = () => import("@/views/Home");
const HomeWork = () => import("@/views/HomeWork");
const UserManage = () => import("@/views/UserManage");
const RoleManage = () => import("@/views/RoleManage");
const CateManage = () => import("@/views/CateManage");
const CarouselManage = () => import("@/views/CarouselManage");
const PetManage = () => import("@/views/PetManage");
const ForumManage = () => import("@/views/ForumManage");
const ForumDetails = () => import("@/views/ForumManage/ForumDetails");

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/home",
    name: "Home",
    component: Home,
    redirect: "/home/work",
    children: [
      {
        path: "/home/work",
        name: "HomeWork",
        component: HomeWork,
      },
      {
        path: "/user/manage",
        name: "UserManage",
        component: UserManage,
      },
      {
        path: "/role/manage",
        name: "RoleManage",
        component: RoleManage,
      },
      {
        path: "/cate/manage",
        name: "CateManage",
        component: CateManage,
      },
      {
        path: "/carousel/manage",
        name: "CarouselManage",
        component: CarouselManage,
      },
      {
        path: "/pet/manage",
        name: "PetManage",
        component: PetManage,
      },
      {
        path: "/forum/manage",
        name: "ForumManage",
        component: ForumManage,
      },
      {
        path: "/forum/details/:id",
        name: "ForumDetails",
        component: ForumDetails,
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 导航守卫
router.beforeEach((to, from, next) => {
  // 得到本地存储的token  想要进其他页面，就要带token
  let token = localStorage.getItem("token");
  // 如果跳转的页面不是登录页且没有token就返回到登录页
  if (to.path !== "/login" && !token) next({ path: "/login" });
  else next();
});

export default router;
